package com.sinosoft.vaccinetoai.dao.redis.configure;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;

/**
 * Redis配置
 * @author xzh
 * @date 2022-10-24 14:38
 * @since 1.0.1
 */
@ConditionalOnProperty(prefix = "spring.redis", name = "host", matchIfMissing = false)
@Configuration
public class RedisConfig {

    /**
     * 配置RedisTemplate
     * @param redisConnectionFactory 连接工厂
     * @return {@link RedisTemplate }<{@link Object }, {@link Object }>
     * @author xzh
     * @since 1.0.1
     */
    @Primary
    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);

        /**
         * 自定义部分（其他都是spring-redis默认的）
         * 添加自定义序列化类(spring默认的不好使)
         */
        template.setDefaultSerializer(RedisSerializer.string());

        return template;
    }

    /**
     * 配置StringRedisTemplate
     * @param redisConnectionFactory 连接工厂
     * @return {@link StringRedisTemplate }
     * @author xzh
     * @since 1.0.1
     */
    @Bean(name = "stringRedisTemplate")
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }

}
